package impl;

import anaydis.sort.Sorter;
import anaydis.sort.SorterType;
import anaydis.sort.gui.ObservableSorter;
import anaydis.sort.gui.SorterListener;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public abstract class AbstractSorter implements Sorter, ObservableSorter {

    public abstract <T> void sort(Comparator<T> tComparator, List<T> ts);

    private SorterType type;
    private List<SorterListener> sorterListeners;

    protected AbstractSorter (SorterType type){
        this.type = type;
        sorterListeners = new ArrayList();
    }

    protected <T> boolean greater(Comparator<T> c, List<T> list, int i, int j){
        for(int k=0; k<sorterListeners.size(); k ++){
            (sorterListeners.get(k)).greater(i,j);
        }
        return c.compare(list.get(i), list.get(j)) > 0;
    }

    protected <T> boolean equals(Comparator<T> c, List<T> list, int i, int j){
        for(int k=0; k<sorterListeners.size(); k ++){
            (sorterListeners.get(k)).equals(i,j);
        }
        return c.compare(list.get(i), list.get(j)) == 0;
    }

    protected <T> void swap(List<T> list, int i, int j){
         for(int k=0; k<sorterListeners.size(); k ++){
            (sorterListeners.get(k)).swap(i,j);
        }
           T aux = list.set(j,list.get(i));
           list.set(i, aux);

    }

    public void addSorterListener(SorterListener sorterListener) {
        sorterListeners.add(sorterListener);
    }

    public void removeSorterListener(SorterListener sorterListener) {
        sorterListeners.remove(sorterListener);
    }

    public void copy(int desde, int hasta, boolean copyToAux){
        for(int k=0; k<sorterListeners.size(); k ++){
            (sorterListeners.get(k)).copy(desde,hasta,copyToAux);
        }
    }
}
